//
//  LocationManager.m
//  atrapalo
//
//  Created by Victor L. Fernandez Rodrigo on 28/07/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LocationManager.h"
#import "Defines.h"

// This is a singleton class, see below
static LocationManager *sharedCLDelegate = nil;

@implementation LocationManager

@synthesize myLocation;


- (void) askLocation {
	[[MyCLController sharedInstance] startUpdates:kCLLocationAccuracyHundredMeters
																 distanceFilter:kCLDistanceFilterNone
																				timeout:20.0
																			 delegado:self];
}

- (void)stopLocation {
    [[MyCLController sharedInstance] stopLocationUpdate];
}

#pragma mark -
#pragma mark CLLocationManager

- (void) didFailUpdatingLocation {
	
}

- (void) timeout:(CLLocation*)res {
	
	self.myLocation = res;
	int latitude = res.coordinate.latitude;
	int longitude = res.coordinate.longitude;
	if (latitude == 0 && longitude == 0) {
		[self askLocation];
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:@"positionUpdated" object:self];

}

- (void) didFinishUpdatingLocation:(CLLocation*)res {
	self.myLocation = res;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"positionUpdated" object:self];
}

- (void) didUpdateLocation:(CLLocation*)res {
	self.myLocation = res;
	[[NSNotificationCenter defaultCenter] postNotificationName:@"positionUpdated" object:self];
    
    NSArray *trackList = [[NSUserDefaults standardUserDefaults] objectForKey:@"tracking"];
    
    for (NSDictionary *fastLocation in trackList) {
        CLLocation *newlocation = [[CLLocation alloc] initWithLatitude:[[fastLocation objectForKey:@"latitut"] doubleValue] longitude:[[fastLocation objectForKey:@"longitut"] doubleValue]];

        double distance = [[[LocationManager sharedInstance] myLocation] distanceFromLocation:newlocation];
        [newlocation release];
        if (distance < 1000) {
            UILocalNotification *localNotif = [[UILocalNotification alloc] init];
            localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
            localNotif.timeZone = [NSTimeZone defaultTimeZone];
            
            // Notification details
            localNotif.alertBody = NSLocalizedString(@"_pisoCerca", @"");
            // Set the action button
            localNotif.alertAction = @"View";
            
            localNotif.soundName = UILocalNotificationDefaultSoundName;
            localNotif.applicationIconBadgeNumber = 0;
            
            // Specify custom data for the notification
            NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[fastLocation objectForKey:@"idPis"] forKey:@"idFlat"];
            localNotif.userInfo = infoDict;
            
            // Schedule the notification
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
            [localNotif release];
        }
    }
    

}

#pragma mark ---- singleton object methods ----

// See "Creating a Singleton Instance" in the Cocoa Fundamentals Guide for more info
// http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html

+ (LocationManager *)sharedInstance {	
	@synchronized(self) {
		if (sharedCLDelegate == nil) {
			sharedCLDelegate = [[self alloc] init]; // assignment not done here
		}
	}
	return sharedCLDelegate;
}

+ (id)allocWithZone:(NSZone *)zone {
	@synchronized(self) {
		if (sharedCLDelegate == nil) {
			sharedCLDelegate = [super allocWithZone:zone];
			return sharedCLDelegate;  // assignment and return on first allocation
		}
	}
	return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
	return self;
}

- (id)retain {
	return self;
}

- (unsigned)retainCount {
	return UINT_MAX;  // denotes an object that cannot be released
}

- (oneway void)release {
	//do nothing
}

- (id)autorelease {
	return self;
}

@end
